package com.zhentao.servicre.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhentao.mapper.UserMapper;
import com.zhentao.model.common.dtos.ResponseResult;
import com.zhentao.model.common.enums.AppHttpCodeEnum;
import com.zhentao.model.user.dto.LoginDto;
import com.zhentao.model.user.pojo.ApUser;
import com.zhentao.servicre.ApUserService;
import com.zhentao.utils.common.AppJwtUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.Map;

@Service
public class ApUserServiceImpl extends ServiceImpl<UserMapper, ApUser> implements ApUserService {
    @Autowired
    private UserMapper userMapper;

    @Override
    public ResponseResult login(LoginDto loginDto) {
        if (StringUtils.isNotEmpty(loginDto.getPhone()) && StringUtils.isNotEmpty(loginDto.getPassword())) {
            String phone = loginDto.getPhone();
            ApUser user = userMapper.getUserByPhone(phone);
            //用户不存在
            if (user == null) {
                return ResponseResult.errorResult(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST, "账号不存在");
            }
            //判断密码
            String salt = user.getSalt();
            String password = DigestUtils.md5DigestAsHex((loginDto.getPassword() + salt).getBytes());
            if (!password.equals(user.getPassword())) {
                return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR, "密码错误");
            }
            //密码正确之后
            String token = AppJwtUtil.getToken(user.getId().longValue());
            Map<String, Object> map = new HashMap<>();
            map.put("user", user);
            map.put("token", token);
            return ResponseResult.okResult(map);
        } else {
            //游客登录，默认id0
            String token = AppJwtUtil.getToken(0L);
            Map<String, Object> map = new HashMap<>();
            map.put("token", token);
            return ResponseResult.okResult(map);
        }

    }
}
